<template>
  <div class="app-container" :style="windowWidth < 1080 ? 'background-color: #f6f8f9;' : ''">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
             :label-width="windowWidth < 1080 ? '100px' : '68px'"
             :style="windowWidth < 1080 ? 'background-color: #fff;padding: 20px 20px 0;' : ''">
      <el-form-item label="所属通道" prop="channelCode">
        <el-select v-model="queryParams.channelCode" placeholder="请选择所属通道" size="small" clearable>
          <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                     :value="item.channelId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置条件</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8"
      :style="windowWidth < 1080 ? 'background-color: #fff;margin:0;padding:0 15px 20px;' : ''">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAdd">
          新增</el-button>
      </el-col>
      <el-col :span="1.5">
<!--        <el-button type="primary" plain size="mini" @click="handleFlagChange">{{ btnText }}</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tradeList" ref="tableDateRef">
      <el-table-column :label="columns[0].label" align="left" prop="channelCode" v-if="columns[0].visible" :key="Math.random()" />
      <el-table-column :label="columns[1].label" align="left" prop="amount" v-if="columns[1].visible" :key="Math.random()" />
      <el-table-column :label="columns[2].label" align="left" prop="num" v-if="columns[2].visible" :key="Math.random()" />
      <el-table-column :label="columns[3].label" align="left" prop="limitnum" v-if="columns[3].visible" :key="Math.random()" />
      <el-table-column :label="columns[4].label" align="left" prop="createTime" v-if="columns[4].visible" :key="Math.random()" />
      <el-table-column :label="columns[5].label" align="left" prop="status" v-if="columns[5].visible" :key="Math.random()">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="columns[6].label" align="left" prop="status" v-if="columns[6].visible" :key="Math.random()">
        <template slot-scope="scope">
<!--          <el-switch v-model="scope.row.fixed" :active-value="0" :inactive-value="1"-->
<!--                     @change="handleFixedChange(scope.row)"></el-switch>-->
          <span v-if="scope.row.fixed == 0" style="color: #f5686f">预拉单模式</span>
          <span v-if="scope.row.fixed == 1" style="color: #00B36B">混合模式</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding"  width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleFixedChange(scope.row)">{{scope.row.fixed == 1 ? '预拉单模式' : '混合模式'}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleFixed(scope.row)">创建固额订单</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看数量</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="addShow" :width="isMobile?'90%':'500px'" append-to-body>
      <el-form ref="form" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="通道" prop="channelId">
          <el-select v-model="addForm.channelCode" placeholder="请选择通道" size="small" clearable>
            <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                       :value="item.channelId" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="addForm.amount" placeholder="金额" size="small" />
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input v-model="addForm.num" placeholder="数量" size="small" />
        </el-form-item>
        <el-form-item label="阙值" prop="limitnum">
          <el-input v-model="addForm.limitnum" placeholder="阙值" size="small" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelFn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="固定金额订单" :visible.sync="fixedShow" :width="isMobile?'90%':'500px'" append-to-body>
      <el-form ref="fixedForm" :model="fixedForm" :rules="addRules" label-width="80px">
        <el-form-item label="金额" prop="amount">
          <el-input v-model="fixedForm.amount" placeholder="金额" size="small" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonFixedLoading" type="primary" @click="submitFixedForm">确 定</el-button>
        <el-button @click="cancelFn">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {
  delfixedConfig, fixedAmountOrder,
  fixedConfigadd,
  fixedConfigedit, fixedConfigFixed,
  fixedConfiglist,
  fixedConfigStatus,
  fixedTradeNum
} from '@/api/merchant/preDrawnSheet'
  import { mapGetters } from 'vuex'
import { listChannel } from '@/api/merchant/channel'
import { initIndexData } from '@/api/merchant'
import { getConfigKeyNew, updateConfig } from '@/api/system/config'

  export default {
    name: "preDrawnSheet",
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        buttonFixedLoading: false,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 订单信息表格数据
        tradeList: [],
        // 弹出层标题
        title: "",
        fixedShow: false,
        fixedForm: {
          channelCode: '',
          amount: '',
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          channelCode: undefined,
        },
        addShow: false,
        addForm: {
          channelCode: '',
          amount: '',
          num: '',
          limitnum: '',
        },
        addRules: {
          amount: [
            { required: true, message: "金额不能为空", trigger: "blur" },
            { pattern: "^[1-9]\\d*$", message: "必须为数字", trigger: "blur" }
          ],

          num: [
            { required: true, message: "数量不能为空", trigger: "blur" },
            { pattern: "^[1-9]\\d*$", message: "必须为数字", trigger: "blur" }
          ],
          limitnum: [{
            required: true,
            message: "阙值不能为空",
            trigger: "blur"
          }],
        },
        // 表单校验
        rules: {},
        // 列信息
        columns: [
          {
            key: 0,
            label: `通道编号`,
            visible: true
          },
          {
            key: 1,
            label: `金额`,
            visible: true
          },
          {
            key: 2,
            label: `数量`,
            visible: true
          },
          {
            key: 3,
            label: `阙值`,
            visible: true
          },
          {
            key: 4,
            label: `创建时间`,
            visible: true
          },
          {
            key: 5,
            label: `状态`,
            visible: true
          },
          {
            key: 6,
            label: `模式`,
            visible: true
          },
        ],
        windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
        channelList: [],
        preDrawnSheeFlagObj: {},
      };
    },
    computed: {
      ...mapGetters(['isMobile']),
      btnText() {
        return this.preDrawnSheeFlagObj.configValue == 'true'?'预拉单模式':'混合模式'
      },
    },
    created() {
      this.getChannelList();
      this.getList();
      getConfigKeyNew({}).then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.preDrawnSheeFlagObj = res.data;
        }
      })
    },
    beforeUpdate() {
       this.$nextTick(() => {
         this.$refs.tableDateRef.doLayout()
       })
    },
    methods: {
      /** 切换模式 */
      handleFlagChange() {
        this.preDrawnSheeFlagObj.configValue = this.preDrawnSheeFlagObj.configValue=='true'?'false':'true';
        let opt = Object.assign({}, this.preDrawnSheeFlagObj);
        delete opt.updateTime;
        updateConfig(opt).then(res => {})
      },
      /** 搜索按钮操作 */
      handleQuery() {
        // this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeCreateTime = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleFixedModule(row) {},
      handleFixed(row) {
        this.fixedForm.channelCode = row.channelCode;
        this.fixedForm.amount = row.amount;
        // this.fixedShow = true;
        fixedAmountOrder(this.fixedForm.amount, this.fixedForm.channelCode).then(res => {
          this.$modal.msgSuccess("创建订单成功");
          // this.buttonFixedLoading = false;
          // this.fixedShow = false;
          this.reset();
          this.getList();
        })
      },
      getChannelList() {
        listChannel(0).then(response => {
          this.channelList = response.data;
          const pages = []
          this.channelList.forEach((item, index) => {
            const page = Math.floor(index / 3) //4代表4条为一行，随意更改
            if (!pages[page]) {
              pages[page] = []
            }
            pages[page].push(item)
          })
          this.channelArray = pages;
        });
      },
      /** 模式修改 */
      handleFixedChange(row) {
        let text = row.fixed == "1" ? "预拉单模式" : "混合模式";
        console.log(row.fixed)
        this.$modal.confirm('确认要切换' + text + '吗？').then(function () {
          return fixedConfigFixed(row.fixedConfigId, row.fixed==0?1:0);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        }).catch(function () {
          // row.fixed = row.fixed === "0" ? "1" : "0";
        });
      },
      /** 状态修改 */
      handleStatusChange(row) {
        let text = row.status == "0" ? "启用" : "停用";
        console.log(row.status)
        this.$modal.confirm('确认要' + text + '该金额吗？').then(function () {
          return fixedConfigStatus(row.fixedConfigId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        fixedConfiglist(this.queryParams).then(response => {
          this.tradeList = response;
          this.loading = false;
        });
      },
      reset() {
        this.addForm = {
          channelCode: '',
          amount: '',
          num: '',
          limitnum: '',
        }
        this.fixedForm = {
          channelCode: '',
          amount: '',
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.addShow = true;
        this.title = "添加预拉单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.addForm.fixedConfigId = row.fixedConfigId;
        this.addForm.channelCode = row.channelCode;
        this.addForm.amount = row.amount + '';
        this.addForm.num = row.num;
        this.addForm.limitnum = row.limitnum;
        this.addShow = true;
        this.title = "修改预拉单";
      },
      cancelFn() {
        this.addShow = false;
        this.buttonFixedLoading = false;
        this.reset();
      },
      submitFixedForm() {
        this.$refs["fixedForm"].validate(valid => {
          if (valid) {
            this.buttonFixedLoading = true;
            fixedAmountOrder(this.fixedForm.amount, this.fixedForm.channelCode).then(res => {
              this.$modal.msgSuccess("创建成功");
              this.buttonFixedLoading = false;
              this.fixedShow = false;
              this.reset();
              this.getList();
            })
          }
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.addForm.fixedConfigId != null) {
              fixedConfigedit(this.addForm).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.addShow = false;
                this.reset();
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              fixedConfigadd(this.addForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.addShow = false;
                this.reset();
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const fixedConfigId = row.fixedConfigId;
        this.$modal.confirm('是否确认删除该预拉单信息吗？').then(() => {
          this.loading = true;
          return delfixedConfig(fixedConfigId);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 查詢商户下还有多少预拉单 */
      handleView(row) {
        fixedTradeNum(1001, row.amount, row.channelCode).then(res => {
          // console.log(res)
          if (res) {
            this.$msgbox(res, '查看数量');
          }
        })
      },
    }
  };

</script>
<style scoped>
  ::v-deep .el-checkbox__inner {
    width: 20px;
    height: 20px;
  }

  ::v-deep .el-checkbox__inner::after {
    top: 2px;
    height: 10px;
    left: 7px;
  }

  .choice {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .choice-item {
    padding: 8px 8px;
    border: 1px solid #999;
    border-radius: 4px;
    margin-right: 20px;
    margin-bottom: 20px;
    cursor: pointer;
  }

</style>
